package filter

import (
	"bytes"
	"github.com/shiningrush/droplet/log"
	"time"

	"github.com/gin-gonic/gin"
)

func RequestLogHandler() gin.HandlerFunc {
	return func(c *gin.Context) {
		start, host, remoteIP, path, method := time.Now(), c.Request.Host, c.ClientIP(), c.Request.URL.Path, c.Request.Method
		query := c.Request.URL.RawQuery

		blw := &bodyLogWriter{body: bytes.NewBuffer(nil), ResponseWriter: c.Writer}
		c.Writer = blw
		c.Next()
		latency := time.Since(start) / 1000000
		statusCode := c.Writer.Status()

		var errs []string
		for _, err := range c.Errors {
			errs = append(errs, err.Error())
		}

		log.Info(
			"\t%s,\tstatus:%d,\thost:%s,\tquery:%s,\tlatency:%v,\tremoteIp:%s,\tmethod:%s\t,errs:%s",
			path, statusCode, host, query, latency, remoteIP, method, errs)
	}
}

type bodyLogWriter struct {
	gin.ResponseWriter
	body *bytes.Buffer
}

func (w bodyLogWriter) Write(b []byte) (int, error) {
	w.body.Write(b)
	return w.ResponseWriter.Write(b)
}
